package com.hsit.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.portlet.bind.annotation.ResourceMapping;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.hsit.dao.PageObj;
import com.hsit.dao.Person;
import com.hsit.service.DogService;

@Controller
@RequestMapping(value = "/dog")
public class DogController {
	
	 private static Logger logger = Logger.getLogger(DogController.class);   

	@Autowired
	private DogService dogService;
	


	@RequestMapping(value="/pp")
	public ModelAndView pp(){
		ModelAndView mav=new ModelAndView();
	List list=new ArrayList();
	for (int i = 0; i < 4; i++) {
		Person person=new Person(""+i+""+"ss", i);
		list.add(person);
	}
		mav.addObject("pp", list);
		mav.setViewName("/dog/test");
		return mav;
	}
	
	
	
	@RequestMapping(value = "/register")
	public void register(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		ModelAndView mav = new ModelAndView();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String email = request.getParameter("email");
		int a = (Integer) dogService.checktwice(username);
		if (a == 0) {
			dogService.register(username, password, email);
		}
		String json = JSON.toJSONString(a);
		response.getWriter().write(json);
		/*
		 * mav.setViewName("redirect:/page/dog/dog.jsp"); return mav;
		 */
	}

	@RequestMapping(value = "/logincheck")
	public void logincheck(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		Integer a = (Integer) dogService.logincheck(username, password);
		if (a > 0) {
			HttpSession session = request.getSession();
			session.setAttribute("username", username);
			logger.info("session已存入用户名-------------"+username);
		}
//		try {
//			Object[] objects=new Object[2];
//			System.out.println(objects[3]);
//		} catch (Exception e) {
//			logger.error(e.getMessage(),e);
//		}
		String json = JSON.toJSONString(a);
		response.getWriter().write(json);

	}

	@RequestMapping(value = "/cleanSession")
	public ModelAndView cleanSession(HttpServletResponse response,
			HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		HttpSession session = request.getSession();
		session.invalidate();
		logger.info("已清空session用户名---------");
		mav.setViewName("redirect:/page/dog/dog.jsp");
		return mav;
	}

	@RequestMapping(value = "/checktwice")
	public void checktwice(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String username = request.getParameter("username");
		Integer a = (Integer) dogService.checktwice(username);
		String json = JSON.toJSONString(a);
		response.getWriter().write(json);

	}

	@RequestMapping(value = "/dogregister")
	public void dogregister(
			@RequestParam(value = "uploadfile") CommonsMultipartFile[] files,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		int dtype = Integer.parseInt(request.getParameter("dtype"));
		/* int dtype = (Integer) dogService.typeId(dtypename); */
		String dname = request.getParameter("dname");
		String dage = request.getParameter("dage");
		String dprice = request.getParameter("dprice");
		String ds = request.getParameter("ds");
		String dstatus = request.getParameter("dstatus");
		if (files != null) {
			for (int i = 0; i < files.length; i++) {
				String filename = files[i].getOriginalFilename();
				String path = request.getSession().getServletContext()
						.getRealPath("/upload/" + filename);
				File file = new File(path);
				int a = (Integer) dogService.imgcheck(filename);
				if (a == 0) {

					try {
						FileUtils.copyInputStreamToFile(
								files[i].getInputStream(), file);
						dogService.dogregister(dtype, dname, dage, dprice, ds,
								filename, dstatus);
					} catch (Exception e) {
						// TODO: handle exception
						e.printStackTrace();
					}

				} else {

				}

				String json = JSON.toJSONString(a);
				response.getWriter().write(json);
			}

		}

	}

	@RequestMapping(value = "/show")
	public void show(HttpServletRequest request, HttpServletResponse response)
			throws UnsupportedEncodingException {
		/* String filename=request.getParameter("img"); */
		String filename = new String(request.getParameter("img").getBytes(
				"iso-8859-1"), "utf-8");
		String path = request.getSession().getServletContext()
				.getRealPath("/upload/" + filename);
		response.setContentType("image/jpeg");
		FileInputStream fis = null;
		OutputStream os = null;
		try {
			fis = new FileInputStream(new File(path));
			os = response.getOutputStream();
			int count = 0;
			byte[] buffer = new byte[1024 * 8];
			while ((count = fis.read(buffer)) != -1) {
				os.write(buffer, 0, count);
				os.flush();

			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {

			try {
				fis.close();
				os.close();
			} catch (Exception e2) {
				// TODO: handle exception
				e2.printStackTrace();
			}

		}

	}

	/*
	 * @RequestMapping(value="/show") public void show(HttpServletRequest
	 * request,HttpServletResponse response,String filename){
	 * filename=request.getParameter("img"); String path =
	 * request.getSession().getServletContext().getRealPath("/upload/" +
	 * filename); response.setContentType("text/html; charset=UTF-8");
	 * FileInputStream fis=null; OutputStream os=null; try { fis=new
	 * FileInputStream(new File(path)); os=response.getOutputStream(); int
	 * i=fis.available();//获取文件大小 byte[] buffer=new byte[i];
	 * fis.read(buffer);//获取文件输入流 fis.close(); os.write(buffer);//输出 os.flush();
	 * os.close();
	 * 
	 * } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }
	 * 
	 * 
	 * }
	 */

	@RequestMapping(value = "/selectDog")
	public ModelAndView selectDog(HttpServletResponse response,
			HttpServletRequest request) {
		List list = dogService.selectTyname();
		String pageNo = request.getParameter("pageNo");
		String dname = request.getParameter("dname");
		String a = request.getParameter("dtypeid");
		if (null == a || "".equals(a)) {
			a = "-1";
		}
		int dtypeid = Integer.parseInt(a);
		if (null == pageNo || "".equals(pageNo)) {
			pageNo = "1";
		}
		int id = Integer.parseInt(pageNo);
		PageObj obj = dogService.selectDog(id, dname, dtypeid);
//		System.out.println(obj.isHasNextPage());
//		System.out.println(obj.getTotalPageCount());
		ModelAndView mav = new ModelAndView();
		request.setAttribute("dname", dname);
		request.setAttribute("dtypeid", dtypeid);
		mav.addObject("obj", obj);
		mav.addObject("list", list);
		mav.setViewName("/dog/doglist");
		return mav;
	}

	@RequestMapping(value = "/selectTyname")
	public void selectTyname(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		List list = dogService.selectTyname();
		String json = JSON.toJSONString(list);
		response.getWriter().write(json);

	}

	@RequestMapping(value = "/Cariadd")
	public void Cariadd(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		ModelAndView mav = new ModelAndView();
		int did = Integer.parseInt(request.getParameter("did"));
		HttpSession session = request.getSession();
		String username = (String) session.getAttribute("username");
		int a = 0;
		if (username == null || "".equals(username)) {
			a = 1;
			String json = JSON.toJSONString(a);
			response.getWriter().write(json);
		} else {
			int id = (Integer) dogService.selectId(username);
			int count = (Integer) dogService.Caricheck(id, did);
			if (count > 0) {
				a = 2;
			} else {
				dogService.Cariadd(id, did);
			}
			String json = JSON.toJSONString(a);
			response.getWriter().write(json);
		}

	}

	@RequestMapping(value = "/SelectCari")
	public ModelAndView SelectCari(HttpServletRequest request)
			throws UnsupportedEncodingException {
		ModelAndView mav = new ModelAndView();
		// 查询购物车
		String username = request.getParameter("username");
		username = URLDecoder.decode(username, "utf-8");
		int id = (Integer) dogService.selectId(username);
		List list = dogService.SelectCari(id);
		List yorderList = dogService.SelectYorder(id, "1");
		List yorderListt = dogService.SelectYorder(id, "2");
		int a = 0;
		// 查询代付款
		List<Map<Object, Object>> allList = new ArrayList<Map<Object, Object>>();
		List<Map<Object, Object>> allListt = new ArrayList<Map<Object, Object>>();
		// List list9=new ArrayList();
		List list2 = dogService.SelectStatus1("1", id);
		List listt2 = dogService.SelectStatus1("2", id);
		for (int i = 0; i < list2.size(); i++) {
			String dnames = "";
			String counts = "";
			Map allmap = new HashMap();
			Map<String, Integer> map = (Map<String, Integer>) list2.get(i);
			for (Map.Entry entry : map.entrySet()) {
				int b = (Integer) entry.getValue();
				a = b;
			}
			List list3 = dogService.SelectStatus1Dname(a);
			List list4 = dogService.SelectStatus1Count(a);
			for (int j = 0; j < list3.size(); j++) {
				Map<String, String> map2 = (Map<String, String>) list3.get(j);
				for (Map.Entry entry2 : map2.entrySet()) {
					String c2 = (String) entry2.getKey();
					dnames += entry2.getValue() + ",";

				}

				Map<String, Integer> map3 = (Map<String, Integer>) list4.get(j);
				for (Map.Entry entry3 : map3.entrySet()) {
					String d2 = (String) entry3.getKey();
					counts += entry3.getValue() + ",";

				}

			}
			String dnames2 = dnames.substring(0, dnames.length() - 1);
			String counts2 = counts.substring(0, counts.length() - 1);
			allmap.put("dname", dnames2);
			allmap.put("count", counts2);
			allList.add(allmap);
			// list9.add("{count="+counts2+", dname="+dnames2+"}");构造出来的List
			// 内部不符合Map<k,v>格式

		}
		for (int i = 0; i < listt2.size(); i++) {
			String dnames = "";
			String counts = "";
			Map allmap = new HashMap();
			Map<String, Integer> map = (Map<String, Integer>) listt2.get(i);
			for (Map.Entry entry : map.entrySet()) {
				int b = (Integer) entry.getValue();
				a = b;
			}
			List list3 = dogService.SelectStatus1Dname(a);
			List list4 = dogService.SelectStatus1Count(a);
			for (int j = 0; j < list3.size(); j++) {
				Map<String, String> map2 = (Map<String, String>) list3.get(j);
				for (Map.Entry entry2 : map2.entrySet()) {
					String c2 = (String) entry2.getKey();
					dnames += entry2.getValue() + ",";

				}

				Map<String, Integer> map3 = (Map<String, Integer>) list4.get(j);
				for (Map.Entry entry3 : map3.entrySet()) {
					String d2 = (String) entry3.getKey();
					counts += entry3.getValue() + ",";

				}

			}
			String dnames2 = dnames.substring(0, dnames.length() - 1);
			String counts2 = counts.substring(0, counts.length() - 1);
			allmap.put("dname", dnames2);
			allmap.put("count", counts2);
			allListt.add(allmap);
			// list9.add("{count="+counts2+", dname="+dnames2+"}");构造出来的List
			// 内部不符合Map<k,v>格式

		}
//		System.out.println(allList);
//		System.out.println(allListt);
//		System.out.println(yorderList);
//		System.out.println(yorderListt);
		// System.out.println(list9);
		mav.addObject("yorderList", yorderList);
		mav.addObject("yorderListt", yorderListt);
		mav.addObject("allList", allList);
		mav.addObject("allListt", allListt);
		mav.addObject("list", list);
		mav.setViewName("/dog/dogtotal");
		return mav;

	}

	@RequestMapping(value = "/deleteCari")
	public void deleteCari(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String ids = request.getParameter("ids");
		dogService.deleteCari(ids);
		List list = dogService.seletDname(ids);
		String json = JSON.toJSONString(list);
		response.getWriter().write(json);

	}

	@RequestMapping(value = "/yorderAdd")
	public void yorderAdd(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String yaddress = request.getParameter("yaddress");
		String yprice = request.getParameter("yprice");
		String dstatus = request.getParameter("dstatus");
		String username = request.getParameter("username");
		int id = (Integer) dogService.selectId(username);
		int yid = dogService.YorderAdd(yaddress, yprice, dstatus, id);

		String dids = request.getParameter("dids");
		String counts = request.getParameter("count");
		String[] b = counts.split(",");
		String[] a = dids.split(",");
		for (int i = 0; i < a.length; i++) {
			int did = Integer.parseInt(a[i]);
			int count = Integer.parseInt(b[i]);
			/*System.out.println("a：" + a[i] + "b:" + b[i]);*/
			dogService.DetailAdd(yid, did, count);
		}

		String json = JSON.toJSONString(1);
		response.getWriter().write(json);

	}

	@RequestMapping(value = "/DeleteAll")
	public void DeleteAll(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String yids = request.getParameter("yids");
		dogService.DeleteDetail(yids);
		dogService.DeleteYorder(yids);
		String json = JSON.toJSONString(yids);
		response.getWriter().write(json);
	}
	
	@RequestMapping(value="/ChangeStatus")
	public void ChangeStatus(HttpServletRequest request,HttpServletResponse response) throws IOException{
		String yids=request.getParameter("yids");
		String yaddress=request.getParameter("yaddress");
		dogService.ChangeStatus(yaddress, yids);
		String json=JSON.toJSONString(yids);
		response.getWriter().write(json);
	}
	@RequestMapping(value="/ChangeDstatus")
	public void ChangeDstatus(HttpServletRequest request,HttpServletResponse response) throws IOException{
		String dstatus=request.getParameter("dstatus");
		int did=Integer.parseInt(request.getParameter("did"));
		if ("上架".equals(dstatus)) {
			dogService.ChangeDstatus(dstatus, did);
			String json=JSON.toJSONString(did);
			response.getWriter().write(json);
		}else {
			dogService.ChangeDstatus(dstatus, did);
			dogService.delete1(did);
			List list=dogService.selectDetailYid(did);
			for (int i = 0; i < list.size(); i++) {
				Map<Object, Object> map=(Map<Object, Object>) list.get(i);
				for(Map.Entry entry:map.entrySet()){
					int yid=(Integer) entry.getValue();
					String ystatus=(String) dogService.selectYorderYstatus(yid);
					if ("1".equals(ystatus)) {
						dogService.deleteDetailAll(yid);
						dogService.deleteYorderAll(yid);
					} else {

					}
				}
			}
			String json=JSON.toJSONString(did);
			response.getWriter().write(json);
		}
		
	}
}
